
#import "ZXLoginRegisterViewController.h"
#import "ZXTabBarController.h"
#import "AFNetworking.h"
@interface ZXLoginRegisterViewController ()<UITextFieldDelegate>
@property(nonatomic,copy)NSString * access_token;
@property (weak, nonatomic) IBOutlet UITextField *userNameF;
@property (weak, nonatomic) IBOutlet UITextField *passWordF;
@property (nonatomic,copy) dispatch_block_t leftBlockAction;
@property(strong ,nonatomic)NSString*testStr;
@property (weak, nonatomic) IBOutlet UIImageView *savepassWordImage;
@property(strong ,nonatomic)NSString*testStr2;
@property(nonatomic)BOOL saveClick;
@end

@implementation ZXLoginRegisterViewController
- (IBAction)savePassWordClick:(UIButton*)sender {
    _saveClick = !_saveClick;
    if (_saveClick) {
        [_savepassWordImage setImage:[UIImage imageNamed:@"keepPassword"]];
    }else [_savepassWordImage setImage:[UIImage imageNamed:@"noKeepPassword"]];
    
}
- (IBAction)loginBtnClick:(UIButton* )sender {
//    [my_AppDelegate.roleArr removeObject:@0];
//    ZXTabBarController * vc = [ZXTabBarController new];
//    [self presentViewController:vc animated:YES completion:^{
//    }];
//    return;
    NSLog(@"%@",_passWordF.text);
    [self.view endEditing:YES];
    if(!_userNameF.text.length){
        [SVProgressHUD showErrorWithStatus:@"账号不能为空"];
        return;
    }
    if(!_passWordF.text.length){
        [SVProgressHUD showErrorWithStatus:@"密码不能为空"];
        return;
    }
    sender.enabled = NO;
    [SVProgressHUD showWithStatus:@"正在登陆"];
    
    dispatch_time_t dipatchTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.0 * NSEC_PER_SEC));
    dispatch_after(dipatchTime, dispatch_get_main_queue(), ^{
        sender.enabled = YES;
    });
    
    NSString *strURL =[[NSString alloc]
                       initWithFormat:@"%@", ZXLoginURL];
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    mutableRequest.HTTPMethod = @"POST";
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:_userNameF.text forKey:@"userName"];
    [param setValue:[MD5Tool MD5ForLower32Bate:_passWordF.text] forKey:@"password"];
    NSData *data = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
    mutableRequest.HTTPBody = data;
    request = [mutableRequest copy];
    NSLog(@"%@", request.allHTTPHeaderFields);
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            sender.enabled = YES;
        
        
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"网络连接失败,请重试"];
            NSLog(@"error == %@",error);
            sender.enabled = YES;
            return ;
        }
        [SVProgressHUD dismiss];
        if (data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"登录返回====%@",dic);
            NSString * statusStr = [NSString stringWithFormat:@"%@",[dic objectForKey:@"msgCod"]];
            
            
            if ([statusStr isEqualToString:@"S0000"]) {
                if (_saveClick) {
                    [[NSUserDefaults standardUserDefaults]setObject:_userNameF.text forKey:@"loginUserName"];
                    [[NSUserDefaults standardUserDefaults]setObject:_passWordF.text forKey:@"loginPassword"];
                }else{
                    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"loginUserName"];
                    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"loginPassword"];
                }
                
                my_AppDelegate.access_token = [[[dic objectForKey:@"data"]objectForKey:@"user"]objectForKey:accessTokenKey];
                my_AppDelegate.nickName = [[[dic objectForKey:@"data"]objectForKey:@"user"]objectForKey:@"nickName"];
                my_AppDelegate.uid = [[[dic objectForKey:@"data"]objectForKey:@"user"]objectForKey:@"uid"];
                my_AppDelegate.userName = [[[dic objectForKey:@"data"]objectForKey:@"user"]objectForKey:@"userName"];
                my_AppDelegate.dealerId = [[[dic objectForKey:@"data"]objectForKey:@"deptData"]objectForKey:@"deptId"];
                NSArray * temArr = [[dic objectForKey:@"data"]objectForKey:@"roleData"];
                if (temArr.count) {
                    my_AppDelegate.roleName = [temArr[0] objectForKey:@"roleName"];
                    for (int i=0; i<temArr.count; i++) {
                        NSString * roleCode=[temArr[i] objectForKey:@"roleCode"];
                        NSString* roleCodechangeString = [roleCode lowercaseString];
//                        NSLog(@"%@",roleCodechangeString);
                        //4s店长
                        if ([roleCodechangeString isEqualToString:@"4sdz"]) {
                            [my_AppDelegate.roleArr removeObject:@1];
                        }else if ([roleCodechangeString isEqualToString:@"adviser"]){
                            //销售顾问
                            [my_AppDelegate.roleArr removeObject:@0];
                        }else if ([roleCodechangeString isEqualToString:@"fqjl"]||[roleCodechangeString isEqualToString:@"dqjl"]){
//                            分区经理->售后店长
                            [my_AppDelegate.roleArr removeObject:@2];
                        }else if ([roleCodechangeString isEqualToString:@"shdz"]){
                            //大区经理->售前督导/大区经理
                            [my_AppDelegate.roleArr removeObject:@3];
                        }else if ([roleCodechangeString isEqualToString:@"shfqjl"]||[roleCodechangeString isEqualToString:@"shdqjl"]){
                            //售后大区经理
                            [my_AppDelegate.roleArr removeObject:@4];
                        }
                        //此句为测试
//                        [my_AppDelegate.roleArr removeObject:@0];
                    }
                }
                
                //0 销售顾问 1售前店长 2 售前督导 3 售后店长
                dispatch_async(dispatch_get_main_queue(), ^{
//                    NSLog(@"用户角色 = %@",my_AppDelegate.roleName);
//                    NSLog(@"用户角色 = %@",my_AppDelegate.roleArr);

                    ZXTabBarController * vc = [ZXTabBarController new];
                    [self presentViewController:vc animated:YES completion:^{
                    }];
                });
            }else{
                NSString * string = [dic objectForKey:@"message"];
                [SVProgressHUD showErrorWithStatus:string];
                [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"loginUserName"];
                [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"loginPassword"];
            }
        }
            });
    }];
                           
    // 启动任务
    [task resume];
    
}
-(void)keyboardWillShow:(NSNotification *)notification{
    [SVProgressHUD dismiss];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField.tag == 300001) {
        _passWordF.text = @"";
    }
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    NSString * loginUserName = [[NSUserDefaults standardUserDefaults] objectForKey:@"loginUserName"];
    NSString * loginPassword =[[NSUserDefaults standardUserDefaults] objectForKey:@"loginPassword"];
    if (textField.tag == 300001) {
        NSLog(@"%@",textField.text);
        if ([textField.text isEqualToString:loginUserName]) {
            _passWordF.text = loginPassword;
        }
    }
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.tag == 300001) {
        [_passWordF becomeFirstResponder];
    }else [self.view endEditing:YES];
    
    return YES;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [SVProgressHUD dismiss];
    [self.view endEditing:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    my_AppDelegate.isyididenglu = 1;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"loginUserName"]) {
        NSString * loginUserName = [[NSUserDefaults standardUserDefaults] objectForKey:@"loginUserName"];
        NSString * loginPassword =[[NSUserDefaults standardUserDefaults] objectForKey:@"loginPassword"];
        _userNameF.text = loginUserName;
        _passWordF.text = loginPassword;
        _saveClick = YES;
        [_savepassWordImage setImage:[UIImage imageNamed:@"keepPassword"]];
    }
//        _userNameF.text = @"test_scrmApp_01";
//        _passWordF.text = @"123456";
  
//    NSString *strURL = [NSString stringWithFormat:@"%@scrmForApp/ideaGuest/1/10?uid=%@&nickName=%@",ZXBaseURL,my_AppDelegate.uid,my_AppDelegate.nickName];
//    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSURL *url = [NSURL URLWithString:strURL];
//    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
//    NSMutableURLRequest *mutableRequest = [request mutableCopy];
//    [mutableRequest addValue:my_AppDelegate.access_token forHTTPHeaderField:accessTokenKey];
//    request = [mutableRequest copy];
//    
//    [HTTPHelper GetHeadmutableRequest:request success:^(NSDictionary *data) {
////        NSLog(@"data = %@",data);
//
//    } failure:^(NSError *error) {
////        NSLog(@"error = %@",error);
//    }];

    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    NSString *str2 = [MD5Tool MD5ForLower32Bate:@"123456"];
    NSLog(@"小写32位:%@", str2);
}
-(void)viewWillAppear:(BOOL)animated{
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:AddCostomerArr];
    my_AppDelegate.roleArr = [NSMutableArray arrayWithObjects:@0,@1,@2,@3,@4,nil];
}
/**
 *  状态栏的样式
 */
- (UIStatusBarStyle)preferredStatusBarStyle
{
    // 白色状态栏
    return UIStatusBarStyleLightContent;
}

@end
